export function hasOwnProperty(obj, key) {
  return Object.prototype.hasOwnProperty(obj, key);
}


const LIFECYCLE_HOOKS = [
  'beforeCreate',
  'created',
  'beforeMount',
  'mounted',
  'beforeUpdate',
  'updated',
  'beforeDestroy',
  'destroyed',
]

// 存储对应的策略
const strats = {};
// 生命周期合并策略
function mergeHook(parentVal, childValue) {
  if (childValue) {
    if (parentVal) {
      return parentVal.concat(childValue);
    } else {
      return [childValue];
    }
  } else {
    return parentVal;
  }
}
LIFECYCLE_HOOKS.forEach(hook => {
  strats[hook] = mergeHook;
})


export function mergeOptions(parent, child) {
  // console.log('mergeOptions', parent, child);
  const options = {};
  // 默认合并策略， 一些属性的合并需要特殊处理，例如: 生命周期 ...
  const mergeFiled = (key) => {
    if (strats[key]) {
      options[key] = strats[key](parent[key], child[key]);
    } else {
      if (typeof parent[key] === 'object' && typeof child[key] === 'object') {
        options[key] = {
          ...parent[key],
          ...child[key]
        }
      } else if (child[key] == null) {
        options[key] = parent[key];
      } else {
        options[key] = child[key];
      }
    }
  }

  for (const p in parent) {
    mergeFiled(p);
  }
  for (const c in child) {
    // 如果上面已经合并过了，就不需要再次合并
    if (!hasOwnProperty(parent, c)) {
      mergeFiled(c);
    }
  }
  return options;
}

export default function initGlobalAPI(Vue) {
  Vue.options = {};

  Vue.mixin = function (options) {

    this.options = mergeOptions(this.options, options);
    return this;
  }
}
